const jwtUtils = require('../utils/jwtUtils');

/**
 * 认证中间件
 * 验证访问令牌并将用户信息附加到上下文
 */
const authMiddleware = async (ctx, next) => {
  // 从请求头获取授权信息
  const authorization = ctx.header.authorization;
  
  if (!authorization) {
    ctx.status = 401;
    ctx.body = {
      success: false,
      message: '缺少授权头'
    };
    return;
  }
  
  // 检查授权格式
  const parts = authorization.split(' ');
  if (parts.length !== 2 || parts[0] !== 'Bearer') {
    ctx.status = 401;
    ctx.body = {
      success: false,
      message: '授权格式错误'
    };
    return;
  }
  
  const token = parts[1];
  
  // 验证访问令牌
  const decoded = jwtUtils.verifyAccessToken(token);
  if (!decoded) {
    ctx.status = 401;
    ctx.body = {
      success: false,
      message: '无效或过期的令牌'
    };
    return;
  }
  
  // 将用户信息附加到上下文
  ctx.state.user = decoded;
  
  await next();
};

/**
 * 角色验证中间件
 * 验证用户是否具有指定角色
 * @param {Array<string>} allowedRoles - 允许的角色列表
 */
const roleMiddleware = (allowedRoles) => {
  return async (ctx, next) => {
    if (!ctx.state.user) {
      ctx.status = 401;
      ctx.body = {
        success: false,
        message: '未授权访问'
      };
      return;
    }
    
    const userRole = ctx.state.user.role;
    
    if (!allowedRoles.includes(userRole)) {
      ctx.status = 403;
      ctx.body = {
        success: false,
        message: '权限不足'
      };
      return;
    }
    
    await next();
  };
};

/**
 * 可选认证中间件
 * 尝试验证访问令牌，但不强制要求
 */
const optionalAuthMiddleware = async (ctx, next) => {
  const authorization = ctx.header.authorization;
  
  if (authorization) {
    const parts = authorization.split(' ');
    if (parts.length === 2 && parts[0] === 'Bearer') {
      const token = parts[1];
      const decoded = jwtUtils.verifyAccessToken(token);
      
      if (decoded) {
        ctx.state.user = decoded;
      }
    }
  }
  
  await next();
};

module.exports = {
  authMiddleware,
  roleMiddleware,
  optionalAuthMiddleware
};